import axios from 'axios'
import store from '@/store/index.js'
import router from '@/router/index.js'
const request = axios.create({
  baseURL: 'http://toutiao.itheima.net' // 配置基地址
})
// 请求拦截器
request.interceptors.request.use(
  function(config) {
    if (store.state.token.length > 0 && config.headers.Authorization === undefined && config.isAuth) {
      config.headers.Authorization = `Bearer ${store.state.token}`
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)
// 响应拦截器
request.interceptors.response.use(
  function(resp) {
    return resp
  },
  async function(err) {
    console.log(err)
    if (err.response.status === 401) {
      store.commit('setToken', '')
      store.commit('setRefreshToken', '')
      router.push(`/login?path=${router.currentRoute.path}`)
    }
    return Promise.reject(err)
  }
)
// 导出自定义函数, 参数对象解构赋值
export default ({ url, method = 'Get', params, data, headers, isAuth = true }) => {
  return request({
    url: url,
    method: method,
    params: params,
    data: data,
    headers: headers,
    isAuth
  })
}
